package cn.edu.seig.textbook.service.impl;


import cn.edu.seig.textbook.domain.pojo.Permissions;
import cn.edu.seig.textbook.domain.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lenovo
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UsersServiceImpl userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users user=userService.getUser(username);
        System.out.println(user);
        if (user==null){
            System.out.println(user.getUsername());
            throw new UsernameNotFoundException(username);
        }

        List<Permissions> authorities = userService.getUserAuthority(username);
        // 对用户权限进行封装
        List<SimpleGrantedAuthority> list = authorities.stream().map(authority-> new SimpleGrantedAuthority(authority.getRole())).collect(Collectors.toList());
        UserDetails userDetails= new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);
        //System.out.println(UserDetailsService.);
        return userDetails;
    }
}
